package com.dilean.common.impl;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.dilean.api.model.Person;
import com.dilean.common.api.DileanMailSender;
import com.dilean.impl.model.attrval.AttrValueText;
import com.dilean.impl.model.attrval.AttrValueTextMultiple;

import static com.dilean.common.DileanAttributes.*;

@Component
public class DileanMailSenderImpl implements DileanMailSender {

	@Autowired 
	private JavaMailSender mailSender;
	
	@Autowired 
	private VelocityEngine velocityEngine;
	
	@Override
	public void sendMail(Person to, Person from, String subject, String text) {
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
					
			AttrValueTextMultiple emailsTo = to.getAttributeValue(ATTR_ID_EMAIL, AttrValueTextMultiple.class);
			helper.setTo(emailsTo.getValue().get(0));
			
			helper.setFrom("dilean-no-reply@gmail.com");
			
			Map<String,Object> model = new HashMap<String,Object>();
			String username;
			username = to.getAttributeValue(ATTR_ID_FIRST_NAME, AttrValueText.class).getValue();
			username = username + " " + to.getAttributeValue(ATTR_ID_LAST_NAME, AttrValueText.class).getValue();
			model.put("personTo", username);
			if (from != null) {
				username = from.getAttributeValue(ATTR_ID_FIRST_NAME, AttrValueText.class).getValue();
				username = username + " " + from.getAttributeValue(ATTR_ID_LAST_NAME, AttrValueText.class).getValue();
				model.put("personFrom", username);
			}
			else model.put("personFrom", "");			
			model.put("text", text);
			String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/emailTemplate.vm", "UTF-8", model );

			helper.setText(emailText,true);
			helper.setSubject(subject);
			
		} catch (MessagingException e) {
			throw new RuntimeException("Wrong mail", e);
		}
		mailSender.send(message);
	}

}
